import React, { useEffect, useState } from 'react'
import { Tabs, PullToRefresh, List, Space, InfiniteScroll, DotLoading, Toast } from 'antd-mobile'
import { StarOutline, EyeOutline } from 'antd-mobile-icons'
import styles from './index.module.less'
import { getArticleData, getProductData } from '../../utils/find/index'
import { useNavigate } from 'react-router-dom'
//接口
interface artType {
  id: string
  author: string
  coverImg?: string
  createTime: string
  title: string
  viewCount?: number
  bigPic?: string
  brandStory?: string
  name?: string
  collect?: number
}
export default function Find() {
  //文章列表
  const [articleList, setArticleList] = useState([])
  //品牌列表数据
  const [productList, setProductList] = useState([])
  const [page, setpage] = useState(1)
  const [pageNum, setPageNum] = useState(5)
  //收藏列表数据
  const [colList, setColList] = useState()
  //切换面板的key值
  const [titleKey, setTitleKey] = useState('article')
  //是否加载更多
  const [hasMore, setHasMore] = useState(true)
  //总数据
  const [total, setTotal] = useState<number>(0)
  //节流
  const [flag, setflag] = useState(false)
  //自定义文本
  const InfiniteScrollContent = ({ hasMore }: { hasMore?: boolean }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 没有更多数据了 ---</span>
        )}
      </>
    )
  }
  //获取文章列表数据
  const getArticleList = async (page: number, pageNum: number) => {
    let res: resType = await getArticleData(page, pageNum)
    console.log(res);
    if (res.code === 20000) {
      let aa = [...articleList, ...res.data.rows] as []
      //循环添加收藏属性
      let newArr: any = []
      aa.map((item) => {
        newArr.push(Object.assign(item, { collect: 0 }))
      })
      //拿到浏览器中存储的值
      let oldList = JSON.parse(localStorage.getItem("artList") as string)
      // console.log("oldList", oldList);
      if (oldList) {
        newArr.forEach((item: any) => {
          oldList.forEach((item1: any) => {
            if (item.id === item1.id) {
              item.collect = item1.collect
            }
          });
        });
      }
      console.log(newArr);
      setArticleList(newArr)
      setTotal(res.data.total)
      setpage(page + 1)
      setTimeout(() => {
        setflag(true)
      }, 3000);
    }
  }
  //加载更多的回调函数
  async function loadMore() {
    //节流阀
    if (flag) {
      setflag(false)
      if (titleKey === "article") {
        await getArticleList(page, pageNum)
        //判断是否有更多数据
        setHasMore(total > articleList.length ? true : false)
      } else {
        await getProductList(page, pageNum)
        setHasMore(total > productList.length ? true : false)
      }
    }
  }
  //获取品牌管理数据
  const getProductList = async (page: number, pageNum: number) => {
    let res: resType = await getProductData(page, pageNum)
    console.log("product", res);
    if (res.code === 20000) {
      setProductList([...productList, ...res.data.rows] as [])
      setTotal(res.data.total)
      setpage(page + 1)
      setTimeout(() => {
        setflag(true)
      }, 3000);
    }
  }
  //tabs标题的切换事件
  const changeHandle = (key: string) => {
    setTitleKey(key)
  }
  //文章详情
  const navegite = useNavigate()
  const articleDetail = (id: string) => {
    //跳转路由
    navegite(`/find/articleInfo?id=${id}`)
  }
  const collectBtn = (index: any, item: artType) => {
    let newList: any = [...articleList]
    if (item.collect) {
      newList[index].collect = 0
      let aa = JSON.parse(localStorage.getItem("artList") as string);
      //更新收藏列表数据 过滤掉取消收藏的那一项
      let bb = aa.filter((item1: any) => item1.id !== item.id)
      localStorage.setItem("artList", JSON.stringify(bb))
      Toast.show({
        icon: 'success',
        content: '取消收藏',
      })
    } else {
      newList[index].collect = 1
      //刷新收藏的文章列表
      getCollectList()
      Toast.show({
        icon: 'success',
        content: '收藏成功',
      })
    }
    setArticleList(newList)
  }
  //收藏的文章列表
  const getCollectList = () => {
    let artListData: any = articleList.filter((item: artType) => item.collect === 1)
    localStorage.setItem("artList", JSON.stringify(artListData))
  }
  useEffect(() => {
    getArticleList(page, pageNum)
    getProductList(page, pageNum)
  }, [])
  return (
    <div className={styles.find_box}>
      <div style={{ position: 'sticky', top: 0, zIndex: 10 }}>
        <Tabs className={styles.find_content} onChange={(key: string) => changeHandle(key)}>
          <Tabs.Tab title='精选文章' key='article' style={{ color: "#ffffff" }} >
          </Tabs.Tab>
          <Tabs.Tab title='品牌列表' key='product' style={{ color: "#ffffff" }}>
          </Tabs.Tab>
        </Tabs>
      </div>
      <div>
        <List className={styles.list}>
          {titleKey === "article" && articleList.map((item: artType, index) => (
            <List.Item key={index} className={styles.art_item} >
              <div className={styles.art_info} onClick={() => articleDetail(item.id)}>
                <img src={item.coverImg} alt="" />
                <div className={styles.art_text}>
                  <h3>{item.title}</h3>
                  <p>{item.author}</p>
                </div>
              </div>
              <div className={styles.art_message}>
                <span><Space><EyeOutline fontSize={24} /> {item.viewCount}</Space> </span>
                <span onClick={() => collectBtn(index, item)}><StarOutline fontSize={24} color={item.collect ? 'red' : '#ccc'} /></span>
              </div>
            </List.Item>
          ))}
          {
            titleKey === "product" && productList.map((item: artType) => (
              <List.Item key={item.id} className={styles.art_item}>
                <div className={styles.pro_item}>
                  <img src={item.bigPic} alt="" className={styles.pro_itemImg} />
                  <p className={styles.pro_name} style={{ color: "#3e3e3e", fontWeight: "bolder" }}>{item.name}</p>
                  <p className={styles.pro_story} style={{ color: "#b1b1b1" }}>{item.brandStory}</p>
                </div>

              </List.Item>
            ))
          }
        </List>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </div>

    </div>
  )
}
